/**
 * Copyright (c) 2017 ucsmy.com, All rights reserved.
 */
package itsm.isperp.module.controller.api.wechat.v2;

import com.fr.form.event.OB;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.DataResponse;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IRole;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.request.JqGridFilter;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.report.ReportDescription;
import itsm.isperp.module.entity.report.ReportDescriptionDetail;
import itsm.isperp.module.service.app.AppRoleService;
import itsm.isperp.module.service.incident.IcdIncidentService;
import itsm.isperp.module.service.report.ReportCheckinDataService;
import itsm.isperp.module.service.report.ReportDescriptionDetailService;
import itsm.isperp.module.service.report.ReportDescriptionService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description:
 * @Author: legen
 * @Created Date: 2017-10-09-0009.
 * @LastModifyDate: 2017-10-09-0009.
 * @LastModifyBy: legen
 * @Version:
 */
@Controller
@RequestMapping("api/wechat/v2/report")
public class ReportController extends BaseController {

    @Autowired
    private ReportDescriptionService reportDescriptionService;

    @Autowired
    private ReportDescriptionDetailService reportDescriptionDetailService;

    @Autowired
    private IcdIncidentService icdIncidentService;

    @Autowired
    private AppRoleService appRoleService;

    private List<Date> getReportBeginAndEndDate(int reportType, Date reportDate)
            throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(reportDate);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        Date begin;
        Date end;
        switch (reportType) {
            case 1:
                begin = reportDate;

                calendar.add(Calendar.DAY_OF_YEAR, 1);
                end = calendar.getTime();
                break;
            case 2:
                int dayofweek = calendar.get(Calendar.DAY_OF_WEEK);
                if (dayofweek == 1) {
                    dayofweek += 7;
                }
                calendar.add(Calendar.DATE, 2 - dayofweek);
                begin = calendar.getTime();

                calendar.add(Calendar.DAY_OF_YEAR, 6);
                end = calendar.getTime();
                break;
            case 3:
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                begin = calendar.getTime();

                calendar.add(Calendar.MONTH, 1);
                calendar.add(Calendar.DAY_OF_YEAR, -1);
                end = calendar.getTime();
                break;
            default:
                throw new Exception("报告类型错误");
        }

        List<Date> result = new ArrayList<Date>();
        result.add(begin);
        result.add(end);
        return result;
    }

    private Map<String, Object> statisticalPersonIndex(String username, Date begin,
                                                       Date end, boolean isServiceDesk, boolean isEngineer) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Map<String, Object> index = new LinkedHashMap<>();
        if (isServiceDesk) {

            JqGridFilter filter = new JqGridFilter();
            filter.addRule("assign_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("assign_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("assigner_id", JqGridFilterRuleOp.eq, username);
            long assignerCount = icdIncidentService.findAllCount(filter);
            index.put("接单数", assignerCount);

            filter = new JqGridFilter();
            filter.addRule("assigner_id", JqGridFilterRuleOp.eq, username);
            filter.addRule("process_id", JqGridFilterRuleOp.in, "SELECT  process_id FROM BPM_ACTION_HISTORY WHERE ACTION_NAME='退回一线' AND action_time >= '" + sdf.format(begin) + "' AND action_time < '" + sdf.format(end) + "'");
            long wrongAssignerCount = icdIncidentService.findAllCount(filter);
            index.put("派单错误数", wrongAssignerCount);

            filter = new JqGridFilter();
            filter.addRule("solved_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("solved_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("solver_id", JqGridFilterRuleOp.eq, username);
            long solverCount = icdIncidentService.findAllCount(filter);
            index.put("处理数", solverCount);

            filter = new JqGridFilter();
            filter.addRule("closed_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("closed_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("assigner_id", JqGridFilterRuleOp.eq, username);
            filter.addRule("feedback_status", JqGridFilterRuleOp.ne, "0");
            long feedbackCount = icdIncidentService.findAllCount(filter);
            index.put("回访数", feedbackCount);
        }
        if (isEngineer) {

            JqGridFilter filter = new JqGridFilter();
            filter.addRule("assign_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("assign_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("supporter_id", JqGridFilterRuleOp.eq, username);
            long assignerCount = icdIncidentService.findAllCount(filter);
            index.put("受理数", assignerCount);

            if (!index.containsKey("处理数")) {
                filter = new JqGridFilter();
                filter.addRule("solved_date", JqGridFilterRuleOp.ge, sdf.format(begin));
                filter.addRule("solved_date", JqGridFilterRuleOp.lt, sdf.format(end));
                filter.addRule("solver_id", JqGridFilterRuleOp.eq, username);
                long solverCount = icdIncidentService.findAllCount(filter);
                index.put("处理数", solverCount);
            }

            filter = new JqGridFilter();
            filter.addRule("supporter_id", JqGridFilterRuleOp.eq, username);
            filter.addRule("solved_date", JqGridFilterRuleOp.isnull, null);
            long leftCount = icdIncidentService.findAllCount(filter);
            index.put("遗留数", leftCount);

            filter.addRule("closed_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("closed_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("supporter_id", JqGridFilterRuleOp.eq, username);
            filter.addRule("feedback_status", JqGridFilterRuleOp.ge, "4");
            long satisfiedCount = icdIncidentService.findAllCount(filter);
            index.put("满意数", satisfiedCount);

            filter.addRule("closed_date", JqGridFilterRuleOp.ge, sdf.format(begin));
            filter.addRule("closed_date", JqGridFilterRuleOp.lt, sdf.format(end));
            filter.addRule("supporter_id", JqGridFilterRuleOp.eq, username);
            filter.addRule("feedback_status", JqGridFilterRuleOp.lt, "4");
            long dissatisfiedCount = icdIncidentService.findAllCount(filter);
            index.put("不满意数", dissatisfiedCount);

        }
        return index;
    }

    private Map<String, Object> getPersonIndex(String username, Integer reportType, Date reportDate, boolean isServiceDesk, boolean isEngineer)
            throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);

        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("id");
        request.addFilterRule("user_name", JqGridFilterRuleOp.eq, username);
        request.addFilterRule("reportType", JqGridFilterRuleOp.eq, reportType.toString());
        request.addFilterRule("report_date", JqGridFilterRuleOp.eq, sdf.format(beginAndEnd.get(0)));
        ReportDescription model = reportDescriptionService.findOneByRequest(request);

        if (model == null) {

            Map<String, Object> index = statisticalPersonIndex(username, beginAndEnd.get(0), beginAndEnd.get(1), isServiceDesk, isEngineer);
            return index;

        } else {

            JqGridRequest detailReuqest = new JqGridRequest();
            detailReuqest.addFilterRule("report_description_id", JqGridFilterRuleOp.eq, model.getId());
            List<Map<String, Object>> maps = reportDescriptionDetailService.findAllDetailByRequest(detailReuqest);

            Map<String, Object> index = new HashMap<>();
            for (Map<String, Object> map : maps) {
                index.put((String) map.get("name"), map.get("value"));
            }

            return index;
        }
    }

    @RequestMapping(value = "getCharts")
    @ResponseBody
    public Map<String, Object> getCharts(String username, int reportType, Date reportDate)
            throws Exception {

        boolean isServiceDesk = false;
        boolean isEngineer = false;
        List<? extends IRole> roles = appRoleService.findRolesByUsername(username);
        for (IRole role : roles) {
            if (role.getName().equals("服务台")) {
                isServiceDesk = true;
            }
            if (!role.getName().equals("服务台")) {
                isEngineer = true;
            }
        }

        Map<String, Object> index = this.getPersonIndex(username, reportType, reportDate, isServiceDesk, isEngineer);

        List<Map<String, Object>> bar = new ArrayList<>();
        List<Map<String, Object>> pie = new ArrayList<>();

        if (isServiceDesk) {
            Map<String, Object> newBar = new LinkedHashMap<>();
            newBar.put("接单数", index.get("接单数"));
            newBar.put("处理数", index.get("处理数"));
            newBar.put("回访数", index.get("回访数"));

            Map<String, Object> barName = new LinkedHashMap<>();
            barName.put("name", "服务台数量报告");
            barName.put("data", newBar);
            bar.add(barName);

            Map<String, Object> newPie = new LinkedHashMap<>();
            Long total = Long.parseLong(index.get("接单数").toString());
            Long wrong = Long.parseLong(index.get("派单错误数").toString());
            Long crrect = total - wrong;
            newPie.put("派单正确数", crrect);
            if (wrong > 0) {
                newPie.put("派单错误数", wrong);
            }

            Map<String, Object> pieName = new LinkedHashMap<>();
            pieName.put("name", "派单正确率");
            pieName.put("data", newPie);
            pie.add(pieName);
        }

        if (isEngineer) {
            Map<String, Object> newBar = new LinkedHashMap<>();
            newBar.put("受理数", index.get("受理数"));
            newBar.put("处理数", index.get("处理数"));
            newBar.put("遗留数", index.get("遗留数"));

            Map<String, Object> barName = new LinkedHashMap<>();
            barName.put("name", "工程师数量报告");
            barName.put("data", newBar);
            bar.add(barName);

            Map<String, Object> newPie = new LinkedHashMap<>();
            newPie.put("满意", index.get("满意数"));
            if (Long.parseLong(index.get("不满意数").toString()) > 0) {
                newPie.put("不满意", index.get("不满意数"));
            }

            Map<String, Object> pieName = new LinkedHashMap<>();
            pieName.put("name", "满意度报告");
            pieName.put("data", newPie);
            pie.add(pieName);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("bar", bar);
        result.put("pie", pie);

        return result;
    }

    @RequestMapping(value = "getChartsById")
    @ResponseBody
    public Map<String, Object> getChartsById(String id)
            throws Exception {

        ReportDescription reportDescription = reportDescriptionService.findOne(id);
        String username = reportDescription.getUserName();

        boolean isServiceDesk = false;
        boolean isEngineer = false;
        List<? extends IRole> roles = appRoleService.findRolesByUsername(username);
        for (IRole role : roles) {
            if (role.getName().equals("服务台")) {
                isServiceDesk = true;
            }
            if (!role.getName().equals("服务台")) {
                isEngineer = true;
            }
        }

        JqGridRequest detailReuqest = new JqGridRequest();
        detailReuqest.addFilterRule("report_description_id", JqGridFilterRuleOp.eq, id);
        List<Map<String, Object>> maps = reportDescriptionDetailService.findAllDetailByRequest(detailReuqest);

        Map<String, Object> index = new HashMap<>();
        for (Map<String, Object> map : maps) {
            index.put((String) map.get("name"), map.get("value"));
        }

        List<Map<String, Object>> bar = new ArrayList<>();
        List<Map<String, Object>> pie = new ArrayList<>();

        if (isServiceDesk) {
            Map<String, Object> newBar = new LinkedHashMap<>();
            newBar.put("接单数", index.get("接单数"));
            newBar.put("处理数", index.get("处理数"));
            newBar.put("回访数", index.get("回访数"));

            Map<String, Object> barName = new LinkedHashMap<>();
            barName.put("name", "服务台数量报告");
            barName.put("data", newBar);
            bar.add(barName);

            Map<String, Object> newPie = new LinkedHashMap<>();
            Long total = Long.parseLong(index.get("接单数").toString());
            Long wrong = Long.parseLong(index.get("派单错误数").toString());
            Long crrect = total - wrong;
            newPie.put("派单正确数", crrect);
            if (wrong > 0) {
                newPie.put("派单错误数", wrong);
            }

            Map<String, Object> pieName = new LinkedHashMap<>();
            pieName.put("name", "派单正确率");
            pieName.put("data", newPie);
            pie.add(pieName);
        }

        if (isEngineer) {
            Map<String, Object> newBar = new LinkedHashMap<>();
            newBar.put("受理数", index.get("受理数"));
            newBar.put("处理数", index.get("处理数"));
            newBar.put("遗留数", index.get("遗留数"));

            Map<String, Object> barName = new LinkedHashMap<>();
            barName.put("name", "工程师数量报告");
            barName.put("data", newBar);
            bar.add(barName);

            Map<String, Object> newPie = new LinkedHashMap<>();
            newPie.put("满意", index.get("满意数"));
            if (Long.parseLong(index.get("不满意数").toString()) > 0) {
                newPie.put("不满意", index.get("不满意数"));
            }

            Map<String, Object> pieName = new LinkedHashMap<>();
            pieName.put("name", "满意度报告");
            pieName.put("data", newPie);
            pie.add(pieName);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("bar", bar);
        result.put("pie", pie);

        return result;
    }

    @RequestMapping(value = "getIndex")
    @ResponseBody
    public Map<String, Object> getIndex(String username, Integer reportType, Date reportDate)
            throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);

        boolean isServiceDesk = false;
        boolean isEngineer = false;
        List<? extends IRole> roles = appRoleService.findRolesByUsername(username);
        for (IRole role : roles) {
            if (role.getName().equals("服务台")) {
                isServiceDesk = true;
            }
            if (!role.getName().equals("服务台")) {
                isEngineer = true;
            }
        }

        Map<String, Object> index = this.getPersonIndex(username, reportType, reportDate, isServiceDesk, isEngineer);

        Map<String, Object> result = new HashMap<>();
        result.put("data", index);

        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("id", "description");
        request.addFilterRule("user_name", JqGridFilterRuleOp.eq, username);
        request.addFilterRule("reportType", JqGridFilterRuleOp.eq, reportType.toString());
        request.addFilterRule("report_date", JqGridFilterRuleOp.eq, sdf.format(beginAndEnd.get(0)));
        ReportDescription model = reportDescriptionService.findOneByRequest(request);
        if (model != null) {
            result.put("id", model.getId());
            result.put("description", model.getDescription());
        }

        return result;
    }

    @RequestMapping(value = "getIndexById")
    @ResponseBody
    public Map<String, Object> getIndexById(String username, String id)
            throws Exception {

        JqGridRequest detailReuqest = new JqGridRequest();
        detailReuqest.addFilterRule("report_description_id", JqGridFilterRuleOp.eq, id);
        List<Map<String, Object>> maps = reportDescriptionDetailService.findAllDetailByRequest(detailReuqest);

        Map<String, Object> index = new HashMap<>();
        for (Map<String, Object> map : maps) {
            index.put((String) map.get("name"), map.get("value"));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("data", index);

        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("description");
        request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
        ReportDescription model = reportDescriptionService.findOneByRequest(request);
        result.put("id", id);
        result.put("description", model.getDescription());

        return result;
    }

    private Map<String, Object> createProjectChats(String projectId, String projectName, Date begin, Date end) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JqGridFilter filter;

        List<Map<String, Object>> bars = new ArrayList<>();

        Map<String, Object> incidentCount = new LinkedHashMap();

        filter = new JqGridFilter();
        filter.addRule("project_id", JqGridFilterRuleOp.eq, projectId);
        filter.addRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        long createCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("新请求", createCount);

        filter = new JqGridFilter();
        filter.addRule("project_id", JqGridFilterRuleOp.eq, projectId);
        filter.addRule("solved_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("solved_date", JqGridFilterRuleOp.lt, sdf.format(end));
        long solverCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("处理数", solverCount);

        filter = new JqGridFilter();
        filter.addRule("project_id", JqGridFilterRuleOp.eq, projectId);
        filter.addRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        filter.addRule("solved_date", JqGridFilterRuleOp.isnull, null);
        long leftCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("遗留数", leftCount);

        Map<String, Object> incidentCountName = new HashedMap();
        incidentCountName.put("name", "数量报告");
        incidentCountName.put("data", incidentCount);
        bars.add(incidentCountName);

        List<Map<String, Object>> gauges = new ArrayList<>();

        Map<String, Object> satisfaction = new LinkedHashMap();


        filter = new JqGridFilter();
        filter.addRule("project_id", JqGridFilterRuleOp.eq, projectId);
        filter.addRule("closed_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("closed_date", JqGridFilterRuleOp.lt, sdf.format(end));
        filter.addRule("feedback_status", JqGridFilterRuleOp.ge, "4");
        long satisfiedCount = icdIncidentService.findAllCount(filter);

        filter = new JqGridFilter();
        filter.addRule("project_id", JqGridFilterRuleOp.eq, projectId);
        filter.addRule("closed_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("closed_date", JqGridFilterRuleOp.lt, sdf.format(end));
        long totalCount = icdIncidentService.findAllCount(filter);

        double satisfactionD = Math.round((double) (satisfiedCount * 100) / totalCount) * 0.01d;
        if (satisfiedCount == 0) {
            satisfactionD = 100;
        }

        satisfaction.put("满意度", satisfactionD);
        Map<String, Object> satisfactionName = new HashedMap();
        satisfactionName.put("name", "满意度");
        satisfactionName.put("data", satisfaction);
        gauges.add(satisfactionName);

        Map<String, Object> project = new HashMap();
        project.put("name", projectName);
        project.put("bars", bars);
        project.put("gauges", gauges);

        return project;
    }

    @RequestMapping(value = "getProjectCharts")
    @ResponseBody
    public List<Map<String, Object>> getProjectCharts(String username, int reportType, Date reportDate)
            throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);
        Date begin = beginAndEnd.get(0);
        Date end = beginAndEnd.get(1);

        JqGridRequest request = new JqGridRequest();
        request.setSelectColumns("DISTINCT project_id", "project_name");
        request.addFilterRule("project_id", JqGridFilterRuleOp.isnotnull, null);
        request.addFilterRule("assign_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        request.addFilterRule("assign_date", JqGridFilterRuleOp.lt, sdf.format(end));
        request.setSort("project_name", Sort.Direction.ASC);
        List<Map<String, Object>> projectNames = this.icdIncidentService.findAllDetailByRequest(request);

        List<Map<String, Object>> result = new LinkedList<>();
        for (Map<String, Object> item : projectNames) {
            String projectId = (String) item.get("project_id");
            String projectName = (String) item.get("project_name");
            Map<String, Object> projectChats = this.createProjectChats(projectId, projectName, begin, end);
            result.add(projectChats);
        }
        return result;
    }

    @RequestMapping(value = "getGeneralCharts")
    @ResponseBody
    public Map<String, Object> getGeneralCharts(String username, int reportType, Date reportDate)
            throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);
        Date begin = beginAndEnd.get(0);
        Date end = beginAndEnd.get(1);

        Map<String, Object> result = new HashedMap();

        JqGridFilter filter;
        Map<String, Object> incidentCount = new LinkedHashMap();

        filter = new JqGridFilter();
        filter.addRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        long createCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("新请求", createCount);

        filter = new JqGridFilter();
        filter.addRule("solved_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("solved_date", JqGridFilterRuleOp.lt, sdf.format(end));
        long solverCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("处理数", solverCount);

        filter = new JqGridFilter();
        filter.addRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        filter.addRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        filter.addRule("solved_date", JqGridFilterRuleOp.isnull, null);
        long leftCount = icdIncidentService.findAllCount(filter);
        incidentCount.put("遗留数", leftCount);

        result.put("0", incidentCount);

        JqGridRequest incidentTypeRequest = new JqGridRequest();
        incidentTypeRequest.setSelectColumns("COUNT(*) count", "incident_type");
        incidentTypeRequest.setGroupBy("incident_type");
        incidentTypeRequest.addFilterRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        incidentTypeRequest.addFilterRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        List<Map<String, Object>> incidentTypes = icdIncidentService.findAllDetailByRequest(incidentTypeRequest);
        Map<String, Object> incidentType = new LinkedHashMap();
        for (Map<String, Object> item : incidentTypes) {
            incidentType.put((String) item.get("incident_type"), item.get("count"));
        }
        result.put("1", incidentType);

        JqGridRequest handleRequest = new JqGridRequest();
        handleRequest.setSelectColumns("COUNT(*) count", "project_name");
        handleRequest.setGroupBy("project_name");
        handleRequest.addFilterRule("project_id", JqGridFilterRuleOp.isnotnull, null);
        handleRequest.addFilterRule("solved_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        handleRequest.addFilterRule("solved_date", JqGridFilterRuleOp.lt, sdf.format(end));
        List<Map<String, Object>> handles = icdIncidentService.findAllDetailByRequest(handleRequest);
        Map<String, Object> handle = new LinkedHashMap();
        for (Map<String, Object> item : handles) {
            handle.put((String) item.get("project_name"), item.get("count"));
        }
        result.put("2", handle);

        JqGridRequest leftRequest = new JqGridRequest();
        leftRequest.setSelectColumns("COUNT(*) count", "project_name");
        leftRequest.setGroupBy("project_name");
        leftRequest.addFilterRule("project_id", JqGridFilterRuleOp.isnotnull, null);
        leftRequest.addFilterRule("create_date", JqGridFilterRuleOp.ge, sdf.format(begin));
        leftRequest.addFilterRule("create_date", JqGridFilterRuleOp.lt, sdf.format(end));
        leftRequest.addFilterRule("solved_date", JqGridFilterRuleOp.isnull, null);
        List<Map<String, Object>> lefts = icdIncidentService.findAllDetailByRequest(leftRequest);
        Map<String, Object> left = new LinkedHashMap();
        for (Map<String, Object> item : lefts) {
            left.put((String) item.get("project_name"), item.get("count"));
        }
        result.put("3", left);

        return result;
    }

    /**
     * 添加描述
     */
    @RequestMapping(value = "describe", method = RequestMethod.POST)
    @ResponseBody
    public void describe(String username, @RequestBody Map<String, Object> data)
            throws Exception {

        login(username);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Integer reportType = Integer.parseInt(data.get("reportType").toString());
        Date reportDate = sdf.parse((String) data.get("reportDate"));

        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);
        Date reportBeginDate = beginAndEnd.get(0);
        String date = sdf.format(reportBeginDate);

        //Map<String, Object> index = (Map<String, Object>) getIndex(username, reportType, reportDate).get("data");

        ReportDescription model = new ReportDescription();
        model.setId(HibernateUUIDGenerator.generate());
        model.setUseId(ContextHolder.getLoginUser().getId());
        model.setUserName(username);
        model.setReportType(reportType);
        model.setReportDate(reportBeginDate);
        model.setDescription((String) data.get("description"));
        model.setCreateDate(new Date());
        
        reportDescriptionService.saveOrUpdate(model);
        
        JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
        
        String sql = "select fullname from app_user where name = '"+username+"'";
        String fullname = jdbcTemplate.queryForList(sql, String.class).get(0);
        
        String sql1 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON a.supporter_name = b.fullname" 
    			+" AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d')"
            		+"WHERE fullname = '"+fullname+"' and report_date like '%"+date+"%'";
            
        String sql2 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"b.fullname = a.creator_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d')" 
			+" WHERE a.`status`!='新建' AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql3 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"b.fullname = a.solver_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d') "
			+"AND a.solution_way = '现场' WHERE (a.`status`='待回访' OR a.`status`='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql4 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d') "+
			"AND (b.fullname = a.`supporter_name` OR b.fullname = a.creator_name) "+
			"WHERE (a.`status`!='待回访' AND a.`status`!='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        Integer orderNum = jdbcTemplate.queryForList(sql1, Integer.class).get(0);
        Integer checkInNum = jdbcTemplate.queryForList(sql2, Integer.class).get(0);
        Integer solutionNum = jdbcTemplate.queryForList(sql3, Integer.class).get(0);
        Integer notFinishNum = jdbcTemplate.queryForList(sql4, Integer.class).get(0);
        
        model.setOrderNum(orderNum);
        model.setCheckInNum(checkInNum);
        model.setSolutionNum(solutionNum);
        model.setNotFinishNum(notFinishNum);
        
        String sql5 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON a.supporter_name = b.fullname" 
    			+" AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d')"
            	+"WHERE fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql6 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"b.fullname = a.creator_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d')" 
    			+" WHERE a.`status`!='新建' AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql7 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"b.fullname = a.solver_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d') "
    			+"AND a.solution_way = '现场' WHERE (a.`status`='待回访' OR a.`status`='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql8 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d') "+
    			"AND (b.fullname = a.`supporter_name` OR b.fullname = a.creator_name) "+
    			"WHERE (a.`status`!='待回访' AND a.`status`!='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        List<String> orderIds = jdbcTemplate.queryForList(sql5, String.class);
        List<String> checkInIds = jdbcTemplate.queryForList(sql6, String.class);
        List<String> solutionIds = jdbcTemplate.queryForList(sql7, String.class);
        List<String> notFinishIds = jdbcTemplate.queryForList(sql8, String.class);
        
        StringBuffer orderId = new StringBuffer();
        StringBuffer checkInId = new StringBuffer();
        StringBuffer solutionId = new StringBuffer();
        StringBuffer notFinishId = new StringBuffer();
        
        for(String id:orderIds){
        	orderId.append(id+",");
        }
        for(String id:checkInIds){
        	checkInId.append(id+",");
        }
        for(String id:solutionIds){
        	solutionId.append(id+",");
        }
        for(String id:notFinishIds){
        	notFinishId.append(id+",");
        }
        if(orderId.toString().length()>0){
        	model.setOrderIds(orderId.substring(0,orderId.length()-1));
        }
        if(checkInId.toString().length()>0){
        	model.setCheckInIds(checkInId.substring(0,checkInId.length()-1));
        }
        if(solutionId.toString().length()>0){
        	model.setSolutionIds(solutionId.substring(0,solutionId.length()-1));
        }
        if(notFinishId.toString().length()>0){
        	model.setNotFinishIds(notFinishId.substring(0,notFinishId.length()-1));
        }
        
        reportDescriptionService.saveOrUpdate(model);
        
        Map<String, Integer> map= new HashMap<String, Integer>();
        map.put("接单数", orderNum);
        map.put("登记数", checkInNum);
        map.put("现场解决数", solutionNum);
        map.put("未完成数", notFinishNum);
        
        
        for(Map.Entry<String, Integer> result : map.entrySet()){
        	ReportDescriptionDetail tempDetail = new ReportDescriptionDetail();
            tempDetail.setReportDescriptionId(model.getId());
            tempDetail.setName(result.getKey());
            tempDetail.setValue(result.getValue().toString());
            
            reportDescriptionDetailService.saveOrUpdate(tempDetail);
        }
        

        /*for (Map.Entry<String, Object> entry : index.entrySet()) {
            ReportDescriptionDetail detail = new ReportDescriptionDetail();
            detail.setReportDescriptionId(model.getId());
            detail.setName(entry.getKey());
            detail.setValue(entry.getValue().toString());

            reportDescriptionDetailService.saveOrUpdate(detail);
        }*/
    }

    @RequestMapping(value = "manage")
    public ModelAndView manage(HttpServletRequest req) {

        ModelAndView mv = new ModelAndView("wechat/v2/reportManage");
        mv.addObject("pageTitle", "个人周报");

        return mv;
    }

    @RequestMapping("listDetailPub")
    @ResponseBody
    public PageResponse<Map<String, Object>> listDetailPub(
            JqGridRequest request, HttpServletRequest req) {
    	JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
    	jdbcTemplate.execute("SET @@sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");
        
        PageResponse<Map<String, Object>> listDetailPub = this.reportDescriptionService.getRepository().findDescriptionDetail(request).toPage();
        return listDetailPub;
    }

    @Autowired
    private ReportCheckinDataService reportCheckinDataService;

    @RequestMapping(value = "checkinManage")
    public ModelAndView checkinManage(HttpServletRequest req) {

        ModelAndView mv = new ModelAndView("wechat/v2/checkinManage");
        mv.addObject("pageTitle", "打卡记录");

        return mv;
    }

    @RequestMapping("listCheckinDetailPub")
    @ResponseBody
    public PageResponse<Map<String, Object>> listCheckinDetailPub(
            JqGridRequest request, HttpServletRequest req) {

        PageResponse<Map<String, Object>> listDetailPub = this.reportCheckinDataService.findAllDetailByRequest(request).toPage();
        return listDetailPub;
    }
    
    @RequestMapping(value = "test")
    @ResponseBody
    public void test(String username,Integer reportType, Date reportDate)
            throws Exception {

        login(username);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        /*Integer reportType = Integer.parseInt(data.get("reportType").toString());
        Date reportDate = sdf.parse((String) data.get("reportDate"));*/

        List<Date> beginAndEnd = getReportBeginAndEndDate(reportType, reportDate);
        Date reportBeginDate = beginAndEnd.get(0);
        String date = sdf.format(reportBeginDate);

        //Map<String, Object> index = (Map<String, Object>) getIndex(username, reportType, reportDate).get("data");

        ReportDescription model = new ReportDescription();
        model.setId(HibernateUUIDGenerator.generate());
        model.setUseId(ContextHolder.getLoginUser().getId());
        model.setUserName(username);
        model.setReportType(reportType);
        model.setReportDate(reportBeginDate);
        //model.setDescription((String) data.get("description"));
        model.setCreateDate(new Date());
        
        reportDescriptionService.saveOrUpdate(model);
        
        JdbcTemplate jdbcTemplate = ContextHolder.getSpringBean("jdbcTemplate");
        
        String sql = "select fullname from app_user where name = '"+username+"'";
        String fullname = jdbcTemplate.queryForList(sql, String.class).get(0);
        
        String sql1 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON a.supporter_name = b.fullname" 
			+" AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d')"
        		+"WHERE fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql2 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"b.fullname = a.creator_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d')" 
			+" WHERE a.`status`!='新建' AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql3 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"b.fullname = a.solver_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d') "
			+"AND a.solution_way = '现场' WHERE (a.`status`='待回访' OR a.`status`='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql4 = "SELECT COUNT(DISTINCT(a.id)) FROM icd_incident a LEFT JOIN v_report_description b ON "+
			"DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d') "+
			"AND (b.fullname = a.`supporter_name` OR b.fullname = a.creator_name) "+
			"WHERE (a.`status`!='待回访' AND a.`status`!='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        Integer orderNum = jdbcTemplate.queryForList(sql1, Integer.class).get(0);
        Integer checkInNum = jdbcTemplate.queryForList(sql2, Integer.class).get(0);
        Integer solutionNum = jdbcTemplate.queryForList(sql3, Integer.class).get(0);
        Integer notFinishNum = jdbcTemplate.queryForList(sql4, Integer.class).get(0);
        
        model.setOrderNum(orderNum);
        model.setCheckInNum(checkInNum);
        model.setSolutionNum(solutionNum);
        model.setNotFinishNum(notFinishNum);
        
        String sql5 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON a.supporter_name = b.fullname" 
    			+" AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d')"
            	+"WHERE fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql6 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"b.fullname = a.creator_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d')" 
    			+" WHERE a.`status`!='新建' AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql7 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"b.fullname = a.solver_name AND DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`solved_date`,'%Y-%m-%d') "
    			+"AND a.solution_way = '现场' WHERE (a.`status`='待回访' OR a.`status`='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        String sql8 = "SELECT DISTINCT(a.id) FROM icd_incident a LEFT JOIN v_report_description b ON "+
    			"DATE_FORMAT(b.report_date,'%Y-%m-%d') = DATE_FORMAT(a.`create_date`,'%Y-%m-%d') "+
    			"AND (b.fullname = a.`supporter_name` OR b.fullname = a.creator_name) "+
    			"WHERE (a.`status`!='待回访' AND a.`status`!='已关闭') AND fullname = '"+fullname+"' and report_date like '%"+date+"%'";
        
        List<String> orderIds = jdbcTemplate.queryForList(sql5, String.class);
        List<String> checkInIds = jdbcTemplate.queryForList(sql6, String.class);
        List<String> solutionIds = jdbcTemplate.queryForList(sql7, String.class);
        List<String> notFinishIds = jdbcTemplate.queryForList(sql8, String.class);
        
        StringBuffer orderId = new StringBuffer();
        StringBuffer checkInId = new StringBuffer();
        StringBuffer solutionId = new StringBuffer();
        StringBuffer notFinishId = new StringBuffer();
        
        for(String id:orderIds){
        	orderId.append(id+",");
        }
        for(String id:checkInIds){
        	checkInId.append(id+",");
        }
        for(String id:solutionIds){
        	solutionId.append(id+",");
        }
        for(String id:notFinishIds){
        	notFinishId.append(id+",");
        }
        if(orderId.toString().length()>0){
        	model.setOrderIds(orderId.substring(0,orderId.length()-1));
        }
        if(checkInId.toString().length()>0){
        	model.setCheckInIds(checkInId.substring(0,checkInId.length()-1));
        }
        if(solutionId.toString().length()>0){
        	model.setSolutionIds(solutionId.substring(0,solutionId.length()-1));
        }
        if(notFinishId.toString().length()>0){
        	model.setNotFinishIds(notFinishId.substring(0,notFinishId.length()-1));
        }
        
        reportDescriptionService.saveOrUpdate(model);
        
        Map<String, Integer> map= new HashMap<String, Integer>();
        map.put("接单数", orderNum);
        map.put("登记数", checkInNum);
        map.put("现场解决数", solutionNum);
        map.put("未完成数", notFinishNum);
        
        
        for(Map.Entry<String, Integer> result : map.entrySet()){
        	ReportDescriptionDetail tempDetail = new ReportDescriptionDetail();
            tempDetail.setReportDescriptionId(model.getId());
            tempDetail.setName(result.getKey());
            tempDetail.setValue(result.getValue().toString());
            
            reportDescriptionDetailService.saveOrUpdate(tempDetail);
        }
        

        /*for (Map.Entry<String, Object> entry : index.entrySet()) {
            ReportDescriptionDetail detail = new ReportDescriptionDetail();
            detail.setReportDescriptionId(model.getId());
            detail.setName(entry.getKey());
            detail.setValue(entry.getValue().toString());

            reportDescriptionDetailService.saveOrUpdate(detail);
        }*/
    }
}
